/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { constants } from "./constants.js";
import { BranchNode } from "./BranchNode.js";
import { isRunning } from "./helper.js";
"use strict";

var __importDefault = this && this.__importDefault || function (mod) {
    return mod && mod.__esModule ? mod : { "default": mod };
};

const constants_1 = constants;
const BranchNode_1 = __importDefault(BranchNode);
// const helper_1 = helper;
/**
 * The Parallel node runs all of its children in parallel and stops running if all of the children are
 * successful or the first one returns failure.
 */
class Parallel extends BranchNode_1.default {
    constructor(blueprint) {
        super(blueprint);
        this.nodeType = 'Parallel';
        this.nodes = blueprint.nodes || [];
        this.numNodes = this.nodes.length;
    }
    run(blackboard = {}, { lastRun, introspector, rerun, registryLookUp = x => x } = {}) {
        if (!rerun) this.blueprint.start(blackboard);
        const results = [];
        for (let currentIndex = 0; currentIndex < this.numNodes; ++currentIndex) {
            const lastRunForIndex = lastRun && lastRun.state[currentIndex];
            if (lastRunForIndex && !(0, isRunning)(lastRunForIndex)) {
                results[currentIndex] = lastRunForIndex;
                continue;
            }
            const node = registryLookUp(this.nodes[currentIndex]);
            const result = node.run(blackboard, { lastRun: lastRunForIndex, introspector, rerun, registryLookUp });
            results[currentIndex] = result;
        }
        const endResult = this.calcResult(results);
        if (!(0, isRunning)(endResult)) {
            this.blueprint.end(blackboard);
        }
        if (introspector) {
            const running = !!results.find(x => (0, isRunning)(x));
            const debugResult = running ? constants_1.RUNNING : endResult;
            introspector.wrapLast(this.numNodes, this, debugResult, blackboard);
        }
        return endResult;
    }
    calcResult(results) {
        if (results.includes(constants_1.FAILURE)) {
            return constants_1.FAILURE;
        }
        const running = !!results.find(x => (0, isRunning)(x));
        return running ? { total: constants_1.RUNNING, state: results } : constants_1.SUCCESS;
    }
}
export { Parallel }